#include <boost/asio.hpp>
#include <boost/asio/ip/icmp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
#include <algorithm>
#include <numeric>
#include <sstream>
#include <iomanip>

// 引入全局变量声明
extern bool working;

using namespace boost::asio;
using namespace boost::asio::ip;
using boost::asio::steady_timer;
namespace bp = boost::placeholders;

// ICMP头部实现
class icmp_header {
public:
    enum { echo_reply = 0, echo_request = 8, time_exceeded = 11 };

    icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }

    void type(unsigned char type) { rep_[0] = type; }
    unsigned char type() const { return rep_[0]; }

    void code(unsigned char code) { rep_[1] = code; }
    unsigned char code() const { return rep_[1]; }

    void checksum(unsigned short checksum) {
        rep_[2] = checksum >> 8;
        rep_[3] = checksum & 0xFF;
    }

    void identifier(unsigned short id) {
        rep_[4] = id >> 8;
        rep_[5] = id & 0xFF;
    }

    void sequence_number(unsigned short seq) {
        rep_[6] = seq >> 8;
        rep_[7] = seq & 0xFF;
    }

    // 计算校验和
    void compute_checksum(const std::string& body) {
        unsigned int sum = (rep_[0] << 8) + rep_[1] + (rep_[4] << 8) + rep_[5] + (rep_[6] << 8) + rep_[7];

        for (std::size_t i = 0; i < body.size(); i += 2) {
            if (i + 1 < body.size())
                sum += (body[i] << 8) + body[i + 1];
            else
                sum += body[i] << 8;
        }

        sum = (sum >> 16) + (sum & 0xFFFF);
        sum += (sum >> 16);
        checksum(static_cast<unsigned short>(~sum));
    }

    boost::asio::const_buffer data() const {
        return boost::asio::buffer(rep_, sizeof(rep_));
    }

    icmp_header(const void* data, std::size_t length) {
        if (length >= sizeof(rep_))
            std::memcpy(rep_, data, sizeof(rep_));
    }

private:
    unsigned char rep_[8];
};

// 辅助函数：将时间转为毫秒
double time_to_ms(const std::chrono::steady_clock::time_point& start, 
                 const std::chrono::steady_clock::time_point& end) {
    return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000.0;
}

// 将毫秒格式化为字符串
std::string format_ms(double ms) {
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(2) << ms << "ms";
    return oss.str();
}

// Ping测试函数
std::string test_ping(std::string& log, const std::string& local_ip, const std::string& target_ip, int count) {
    log.clear();
    log += "开始执行Ping测试... 从 " + local_ip + " 向 " + target_ip + " 发送 " + std::to_string(count) + " 个请求\n";
    
    try {
        // 先验证IP地址是否有效
        boost::system::error_code ec;
        auto local_addr = make_address(local_ip, ec);
        if (ec) {
            log += "错误：本地IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        auto target_addr = make_address(target_ip, ec);
        if (ec) {
            log += "错误：目标IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        io_context io;
        icmp::socket socket(io, icmp::v4());
        
        // 尝试绑定到本地IP（指定网卡）
        try {
            socket.bind(icmp::endpoint(local_addr, 0));
        } catch (const std::exception& e) {
            log += "绑定本地IP地址失败: " + std::string(e.what()) + " 请检查本地IP地址是否正确，或者程序是否有管理员权限\n";
            return "[不通过]";
        }
        
        // 构造目标终结点
        icmp::endpoint target(target_addr, 0);
        
        std::vector<double> response_times;
        int success_count = 0;
        
        for (int seq = 0; seq < count; ++seq) {
            // 检查是否需要中断测试
            if (!working) {
                log += "测试被用户中断\n";
                if (success_count > 0) {
                    double loss_rate = (seq - success_count) * 100.0 / seq;
                    double avg_time = 0;
                    if (!response_times.empty()) {
                        avg_time = std::accumulate(response_times.begin(), response_times.end(), 0.0) / response_times.size();
                    }
                    return "[中断：" + std::to_string(static_cast<int>(loss_rate)) + "% 丢包率 " + format_ms(avg_time) + "平均延迟]";
                } else {
                    return "[用户中断]";
                }
            }
            
            // 构造ICMP请求包
            std::string body("abcdefghijklmnopqrstuvwxyz");
            icmp_header header;
            header.type(icmp_header::echo_request);
            header.code(0);
            header.identifier(static_cast<unsigned short>(::GetCurrentProcessId()));
            header.sequence_number(static_cast<unsigned short>(seq));
            header.compute_checksum(body);
            
            // 记录发送时间
            auto start_time = std::chrono::steady_clock::now();
            
            // 发送请求 - 分开构建缓冲区
            std::vector<boost::asio::const_buffer> buffers;
            buffers.push_back(boost::asio::buffer(&header, sizeof(header)));
            buffers.push_back(boost::asio::buffer(body));
            socket.send_to(buffers, target);
            
            // 设置超时
            steady_timer timer(io, std::chrono::seconds(2));
            bool replied = false;
            
            // 接收缓冲区
            std::vector<char> recv_buf(1024);
            icmp::endpoint sender;
            
            // 异步接收
            socket.async_receive_from(
                buffer(recv_buf), sender,
                [&](const boost::system::error_code& ec, std::size_t bytes_received) {
                    if (!ec) {
                        auto end_time = std::chrono::steady_clock::now();
                        double ms = time_to_ms(start_time, end_time);
                        
                        // 解析ICMP响应
                        if (bytes_received >= sizeof(icmp_header)) {
                            icmp_header recv_header(&recv_buf[20], bytes_received - 20);
                            if (recv_header.type() == icmp_header::echo_reply) {
                                success_count++;
                                response_times.push_back(ms);
                                log += "来自 " + sender.address().to_string() + " 的回复: 字节=32 时间=" + format_ms(ms) + "\n";
                                //std::cout << "来自 " + sender.address().to_string() + " 的回复: 字节=32 时间=" + format_ms(ms) + "\n";
                                //std::cout.flush();
                                replied = true;
                                timer.cancel();
                            }
                        }
                    }
                });
            
            // 超时处理
            timer.async_wait([&](const boost::system::error_code& ec) {
                if (!ec && !replied) {
                    log += "请求超时\n";
                    socket.cancel();
                }
            });
            
            // 运行事件循环，处理异步操作
            io.run();
            io.restart();
            
            // 适当延时
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }
        
        // 计算统计信息
        double loss_rate = (count - success_count) * 100.0 / count;
        
        log += "统计信息: 数据包: 已发送 = " + std::to_string(count) + "，已接收 = " + std::to_string(success_count) + 
               "，丢失 = " + std::to_string(count - success_count) + " (" + std::to_string(static_cast<int>(loss_rate)) + "% 丢失)\n";
        
        if (!response_times.empty()) {
            double min_time = *std::min_element(response_times.begin(), response_times.end());
            double max_time = *std::max_element(response_times.begin(), response_times.end());
            double avg_time = std::accumulate(response_times.begin(), response_times.end(), 0.0) / response_times.size();
            
            log += "往返行程的估计时间(以毫秒为单位): 最短 = " + format_ms(min_time) + "，最长 = " + format_ms(max_time) + "，平均 = " + format_ms(avg_time) + "\n";
            
            return "[通过：" + std::to_string(static_cast<int>(loss_rate)) + "% 丢包率 " + format_ms(avg_time) + "平均延迟]";
        } else {
            return "[不通过]";
        }
    }
    catch (std::exception& e) {
        log += "发生错误: " + std::string(e.what()) + "\n";
        return "[不通过]";
    }
}

// Telnet测试函数
std::string test_telnet(std::string& log, const std::string& local_ip, const std::string& target_ip, int port) {
    log.clear();
    log += "开始执行Telnet测试... 从 " + local_ip + " 连接到 " + target_ip + ":" + std::to_string(port) + "\n";
    
    try {
        // 检查是否需要中断测试
        if (!working) {
            log += "测试被用户中断\n";
            return "[用户中断]";
        }
        
        // 先验证IP地址是否有效
        boost::system::error_code ec;
        auto local_addr = make_address(local_ip, ec);
        if (ec) {
            log += "错误：本地IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        auto target_addr = make_address(target_ip, ec);
        if (ec) {
            log += "错误：目标IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        io_context io;
        tcp::socket socket(io);
        
        // 尝试绑定到本地IP（指定网卡）
        try {
            tcp::endpoint local_endpoint(local_addr, 0);
            socket.open(tcp::v4());
            socket.bind(local_endpoint);
        } catch (const std::exception& e) {
            log += "绑定本地IP地址失败: " + std::string(e.what()) + " 请检查本地IP地址是否正确\n";
            return "[不通过]";
        }
        
        // 设置连接超时
        steady_timer timeout(io, std::chrono::seconds(5));
        bool connected = false;
        
        // 连接到目标
        tcp::endpoint remote_endpoint(target_addr, port);
        
        // 开始连接的时间
        auto start_time = std::chrono::steady_clock::now();
        
        // 异步连接
        socket.async_connect(remote_endpoint, [&](const boost::system::error_code& ec) {
            if (!ec) {
                auto end_time = std::chrono::steady_clock::now();
                double ms = time_to_ms(start_time, end_time);
                connected = true;
                log += "连接成功，耗时 " + format_ms(ms) + "\n";
                timeout.cancel();
            } else {
                log += "连接失败: " + ec.message() + "\n";
            }
        });
        
        // 超时处理
        timeout.async_wait([&](const boost::system::error_code& ec) {
            if (!ec && !connected) {
                log += "连接超时\n";
                socket.close();
            }
        });
        
        // 运行事件循环，处理异步操作
        io.run();
        
        // 如果连接成功，关闭连接
        if (connected) {
            socket.close();
            log += " 断开连接\n";
            return "[通过]";
        } else {
            return "[不通过]";
        }
    }
    catch (std::exception& e) {
        log += "发生错误: " + std::string(e.what()) + "\n";
        return "[不通过]";
    }
}

// tracert测试函数
std::string test_tracert(std::string& log, const std::string& local_ip, const std::string& target_ip, const std::string& protocol, int timeout, int attempts) {
    log.clear();
    log += "开始执行 Tracert 测试... 从 " + local_ip + " 追踪到 " + target_ip + " 的路由 最大跃点数为 30 协议为 " + protocol + "\n";
    
    try {
        int hops = 0;
        int effective_hops = 0; // 实际有效跳数
        
        // 检查是否需要中断测试
        if (!working) {
            log += "测试被用户中断\n";
            return "[用户中断]";
        }
        
        // 先验证IP地址是否有效
        boost::system::error_code ec;
        auto local_addr = make_address(local_ip, ec);
        if (ec) {
            log += "错误：本地IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        auto target_addr = make_address(target_ip, ec);
        if (ec) {
            log += "错误：目标IP地址无效 - " + ec.message() + "\n";
            return "[不通过]";
        }
        
        io_context io;
        
        // 根据协议类型创建不同的socket
        icmp::socket icmp_socket(io, icmp::v4());
        udp::socket udp_socket(io);
        tcp::socket tcp_socket(io);
        
        // 存储所有已发现的路由节点IP
        std::vector<std::string> route_nodes;
        
        // 设置超时时间
        int timeout_ms = timeout;
        
        // 根据协议类型进行不同的初始化
        if (protocol == "ICMP") {
            // 尝试绑定到本地IP（指定网卡）
            try {
                icmp_socket.bind(icmp::endpoint(local_addr, 0));
            } catch (const std::exception& e) {
                log += "绑定本地IP地址失败: " + std::string(e.what()) + " 请检查本地IP地址是否正确，或者程序是否有管理员权限\n";
                return "[不通过]";
            }
        } else if (protocol == "UDP") {
            try {
                udp_socket.open(udp::v4());
                udp_socket.bind(udp::endpoint(local_addr, 0));
            } catch (const std::exception& e) {
                log += "绑定本地IP地址失败: " + std::string(e.what()) + " 请检查本地IP地址是否正确\n";
                return "[不通过]";
            }
        } else if (protocol == "TCP") {
            try {
                tcp_socket.open(tcp::v4());
                tcp_socket.bind(tcp::endpoint(local_addr, 0));
            } catch (const std::exception& e) {
                log += "绑定本地IP地址失败: " + std::string(e.what()) + " 请检查本地IP地址是否正确\n";
                return "[不通过]";
            }
        } else {
            log += "不支持的协议类型: " + protocol + "，支持的协议类型包括: ICMP, UDP, TCP\n";
            return "[不通过]";
        }
        
        // 构造目标终结点
        icmp::endpoint icmp_target(target_addr, 0);
        udp::endpoint udp_target(target_addr, 33434); // 标准traceroute的UDP起始端口
        tcp::endpoint tcp_target(target_addr, 80);    // 使用HTTP端口作为目标
        
        bool reached_destination = false;
        
        for (int ttl = 1; ttl <= 30; ++ttl) {
            // 检查是否需要中断测试
            if (!working) {
                log += "测试被用户中断，共完成 " + std::to_string(ttl-1) + " 跳\n";
                return "[中断：" + std::to_string(ttl-1) + "跳]";
            }
            
            hops++;
            
            // 设置IP_TTL选项
            if (protocol == "ICMP") {
                icmp_socket.set_option(unicast::hops(ttl));
            } else if (protocol == "UDP") {
                udp_socket.set_option(unicast::hops(ttl));
            } else if (protocol == "TCP") {
                tcp_socket.set_option(unicast::hops(ttl));
            }
            
            // 设置尝试的结果
            std::vector<double> attempt_times;
            std::string hop_addr;
            bool reached_target = false;
            int successful_attempts = 0;
            
            // 测试结果字符串 - Windows格式的tracert
            std::string hop_info = "  " + std::to_string(ttl) + "    ";
            
            // 每个跳点执行attempts次测试
            for (int attempt = 0; attempt < attempts; ++attempt) {
                // 接收缓冲区
                std::vector<char> recv_buf(1024);
                icmp::endpoint sender;
                boost::system::error_code recv_error;
                
                auto start_time = std::chrono::steady_clock::now();
                
                // 根据协议类型发送请求
                if (protocol == "ICMP") {
                    // 构造ICMP请求包
                    std::string body("TraceRouteData");
                    icmp_header header;
                    header.type(icmp_header::echo_request);
                    header.code(0);
                    header.identifier(static_cast<unsigned short>(::GetCurrentProcessId()));
                    header.sequence_number(static_cast<unsigned short>(ttl * 10 + attempt));
                    header.compute_checksum(body);
                    
                    // 发送请求 - 分开构建缓冲区
                    std::vector<boost::asio::const_buffer> buffers;
                    buffers.push_back(boost::asio::buffer(&header, sizeof(header)));
                    buffers.push_back(boost::asio::buffer(body));
                    icmp_socket.send_to(buffers, icmp_target);
                    
                    // 非阻塞模式接收
                    icmp_socket.non_blocking(true);
                    
                    // 设置超时时间
                    boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(timeout_ms));
                    bool timeout_occurred = false;
                    
                    // 设置超时处理
                    timer.async_wait([&](const boost::system::error_code& error) {
                        if (!error) {
                            timeout_occurred = true;
                            icmp_socket.cancel();
                        }
                    });
                    
                    // 尝试接收数据 - 增加多次轮询以确保能接收到所有回复
                    std::size_t bytes_recvd = 0;
                    std::chrono::steady_clock::time_point start_poll = std::chrono::steady_clock::now();
                    
                    while (!timeout_occurred && 
                           std::chrono::duration_cast<std::chrono::milliseconds>(
                               std::chrono::steady_clock::now() - start_poll).count() < timeout_ms) {
                        bytes_recvd = icmp_socket.receive_from(
                            boost::asio::buffer(recv_buf), 
                            sender, 
                            0, 
                            recv_error
                        );
                        
                        // 如果有错误但不是"would block"
                        if (recv_error && recv_error != boost::asio::error::would_block) {
                            break;
                        }
                        
                        // 如果接收到数据
                        if (bytes_recvd > 0) {
                            auto end_time = std::chrono::steady_clock::now();
                            double ms = time_to_ms(start_time, end_time);
                            
                            // 检查接收到的ICMP包类型
                            if (bytes_recvd >= 28) { // IP头(20) + ICMP头(8)
                                // IP包头后的ICMP包，IP包头通常是20字节
                                icmp_header recv_header(&recv_buf[20], bytes_recvd - 20);
                                
                                // 检查接收到的ICMP包类型
                                bool valid_response = false;
                                
                                // 时间超时包 (TTL expired)
                                if (recv_header.type() == icmp_header::time_exceeded) {
                                    valid_response = true;
                                }
                                // 或Echo Reply (已到达目标)
                                else if (recv_header.type() == icmp_header::echo_reply) {
                                    valid_response = true;
                                    reached_target = true;
                                }
                                
                                if (valid_response) {
                                    // 保存时间
                                    attempt_times.push_back(ms);
                                    successful_attempts++;
                                    
                                    // 保存地址
                                    if (hop_addr.empty()) {
                                        hop_addr = sender.address().to_string();
                                        
                                        // 检查是否是新的路由节点
                                        bool is_new_node = true;
                                        for (const auto& node : route_nodes) {
                                            if (node == hop_addr) {
                                                is_new_node = false;
                                                break;
                                            }
                                        }
                                        
                                        if (is_new_node) {
                                            route_nodes.push_back(hop_addr);
                                            effective_hops++;
                                        }
                                    }
                                    
                                    // 检查是否已到达目标
                                    if (sender.address() == target_addr) {
                                        reached_target = true;
                                    }
                                    
                                    timer.cancel(); // 取消定时器
                                    break; // 已收到有效响应，跳出轮询循环
                                }
                            }
                        }
                        
                        // 尝试处理所有可用事件
                        io.poll();
                        
                        // 短暂等待一下，避免CPU过载
                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    }
                    
                    // 取消计时器
                    timer.cancel();
                    
                    // 将socket恢复为阻塞模式
                    icmp_socket.non_blocking(false);
                } 
                else if (protocol == "UDP") {
                    // 设置接收ICMP错误响应的socket
                    icmp::socket error_socket(io, icmp::v4());
                    error_socket.bind(icmp::endpoint(local_addr, 0));
                    
                    // 根据尝试次数动态调整目标端口
                    udp::endpoint current_target(target_addr, 33434 + ttl * 10 + attempt);
                    
                    // 发送UDP数据包
                    std::string data("TraceRouteData");
                    udp_socket.send_to(boost::asio::buffer(data), current_target);
                    
                    // 非阻塞模式接收ICMP错误
                    error_socket.non_blocking(true);
                    
                    // 设置超时
                    boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(timeout_ms));
                    bool timeout_occurred = false;
                    
                    timer.async_wait([&](const boost::system::error_code& error) {
                        if (!error) {
                            timeout_occurred = true;
                            error_socket.cancel();
                        }
                    });
                    
                    // 接收ICMP错误报文
                    std::size_t bytes_recvd = 0;
                    std::chrono::steady_clock::time_point start_poll = std::chrono::steady_clock::now();
                    
                    while (!timeout_occurred && 
                           std::chrono::duration_cast<std::chrono::milliseconds>(
                               std::chrono::steady_clock::now() - start_poll).count() < timeout_ms) {
                        bytes_recvd = error_socket.receive_from(
                            boost::asio::buffer(recv_buf), 
                            sender, 
                            0, 
                            recv_error
                        );
                        
                        if (recv_error && recv_error != boost::asio::error::would_block) {
                            break;
                        }
                        
                        if (bytes_recvd > 0) {
                            auto end_time = std::chrono::steady_clock::now();
                            double ms = time_to_ms(start_time, end_time);
                            
                            // 这里我们希望收到"TTL超时"或"端口不可达"等ICMP错误
                            if (bytes_recvd >= 28) { // IP头(20) + ICMP头(8)
                                icmp_header recv_header(&recv_buf[20], bytes_recvd - 20);
                                
                                bool valid_response = false;
                                
                                // 时间超时
                                if (recv_header.type() == icmp_header::time_exceeded) {
                                    valid_response = true;
                                }
                                // 端口不可达（目标到达）
                                else if (recv_header.type() == 3 && recv_header.code() == 3) { // ICMP端口不可达
                                    valid_response = true;
                                    reached_target = true;
                                }
                                
                                if (valid_response) {
                                    attempt_times.push_back(ms);
                                    successful_attempts++;
                                    
                                    if (hop_addr.empty()) {
                                        hop_addr = sender.address().to_string();
                                        
                                        bool is_new_node = true;
                                        for (const auto& node : route_nodes) {
                                            if (node == hop_addr) {
                                                is_new_node = false;
                                                break;
                                            }
                                        }
                                        
                                        if (is_new_node) {
                                            route_nodes.push_back(hop_addr);
                                            effective_hops++;
                                        }
                                    }
                                    
                                    if (sender.address() == target_addr) {
                                        reached_target = true;
                                    }
                                    
                                    timer.cancel();
                                    break;
                                }
                            }
                        }
                        
                        io.poll();
                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    }
                    
                    timer.cancel();
                    error_socket.non_blocking(false);
                    error_socket.close();
                }
                else if (protocol == "TCP") {
                    // 根据尝试次数动态调整目标端口
                    tcp::endpoint current_target(target_addr, 80 + attempt);
                    
                    // 准备接收ICMP错误
                    icmp::socket error_socket(io, icmp::v4());
                    error_socket.bind(icmp::endpoint(local_addr, 0));
                    
                    // 尝试TCP连接
                    boost::system::error_code connect_error;
                    tcp_socket.async_connect(current_target,
                        [&](const boost::system::error_code& ec) {
                            connect_error = ec;
                        });
                    
                    // 设置超时
                    boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(timeout_ms));
                    bool timeout_occurred = false;
                    
                    timer.async_wait([&](const boost::system::error_code& error) {
                        if (!error) {
                            timeout_occurred = true;
                            tcp_socket.close();
                            error_socket.cancel();
                        }
                    });
                    
                    // 同时监控TCP连接结果和ICMP错误
                    error_socket.non_blocking(true);
                    
                    std::size_t bytes_recvd = 0;
                    std::chrono::steady_clock::time_point start_poll = std::chrono::steady_clock::now();
                    
                    bool connection_success = false;
                    
                    while (!timeout_occurred && 
                           std::chrono::duration_cast<std::chrono::milliseconds>(
                               std::chrono::steady_clock::now() - start_poll).count() < timeout_ms) {
                        // 监听ICMP错误
                        bytes_recvd = error_socket.receive_from(
                            boost::asio::buffer(recv_buf), 
                            sender, 
                            0, 
                            recv_error
                        );
                        
                        // 处理ICMP错误
                        if (bytes_recvd > 0) {
                            auto end_time = std::chrono::steady_clock::now();
                            double ms = time_to_ms(start_time, end_time);
                            
                            if (bytes_recvd >= 28) {
                                icmp_header recv_header(&recv_buf[20], bytes_recvd - 20);
                                
                                bool valid_response = false;
                                
                                // 时间超时
                                if (recv_header.type() == icmp_header::time_exceeded) {
                                    valid_response = true;
                                }
                                
                                if (valid_response) {
                                    attempt_times.push_back(ms);
                                    successful_attempts++;
                                    
                                    if (hop_addr.empty()) {
                                        hop_addr = sender.address().to_string();
                                        
                                        bool is_new_node = true;
                                        for (const auto& node : route_nodes) {
                                            if (node == hop_addr) {
                                                is_new_node = false;
                                                break;
                                            }
                                        }
                                        
                                        if (is_new_node) {
                                            route_nodes.push_back(hop_addr);
                                            effective_hops++;
                                        }
                                    }
                                    
                                    timer.cancel();
                                    break;
                                }
                            }
                        }
                        
                        // 处理TCP连接结果
                        if (!connect_error) {
                            auto end_time = std::chrono::steady_clock::now();
                            double ms = time_to_ms(start_time, end_time);
                            
                            attempt_times.push_back(ms);
                            successful_attempts++;
                            
                            if (hop_addr.empty()) {
                                hop_addr = target_addr.to_string();
                                
                                bool is_new_node = true;
                                for (const auto& node : route_nodes) {
                                    if (node == hop_addr) {
                                        is_new_node = false;
                                        break;
                                    }
                                }
                                
                                if (is_new_node) {
                                    route_nodes.push_back(hop_addr);
                                    effective_hops++;
                                }
                            }
                            
                            reached_target = true;
                            connection_success = true;
                            timer.cancel();
                            break;
                        } else if (connect_error != boost::asio::error::would_block && 
                                  connect_error != boost::asio::error::in_progress &&
                                  connect_error != boost::asio::error::operation_aborted) {
                            // 连接失败但不是超时
                            if (ttl == 30) {  // 最后一跳，可能是目标拒绝连接
                                auto end_time = std::chrono::steady_clock::now();
                                double ms = time_to_ms(start_time, end_time);
                                
                                attempt_times.push_back(ms);
                                successful_attempts++;
                                
                                if (hop_addr.empty()) {
                                    hop_addr = target_addr.to_string();
                                    
                                    bool is_new_node = true;
                                    for (const auto& node : route_nodes) {
                                        if (node == hop_addr) {
                                            is_new_node = false;
                                            break;
                                        }
                                    }
                                    
                                    if (is_new_node) {
                                        route_nodes.push_back(hop_addr);
                                        effective_hops++;
                                    }
                                }
                                
                                reached_target = true;
                                connection_success = true;
                                timer.cancel();
                                break;
                            }
                        }
                        
                        io.poll();
                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    }
                    
                    timer.cancel();
                    error_socket.non_blocking(false);
                    error_socket.close();
                    
                    // 确保TCP socket关闭并重新打开以准备下一次尝试
                    tcp_socket.close();
                    tcp_socket.open(tcp::v4());
                    tcp_socket.bind(tcp::endpoint(local_addr, 0));
                }
                
                // 如果没有收到有效响应，记录超时
                if (attempt_times.size() <= attempt) {
                    attempt_times.push_back(-1); // -1 表示超时
                }
                
                // 重置io_context
                io.restart();
                
                // 延时一小段时间，让网络稍微休息
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }
            
            // 格式化跳数信息（与Windows tracert命令完全一致）
            for (int i = 0; i < 3; i++) {
                if (i < attempt_times.size() && attempt_times[i] >= 0) {
                    // 与Windows tracert保持一致的格式："  1 ms     1 ms     1 ms  "
                    hop_info += std::to_string(static_cast<int>(attempt_times[i])) + " ms    ";
                } else {
                    hop_info += "*        ";
                }
            }
            
            // 添加IP地址信息
            if (!hop_addr.empty()) {
                hop_info += hop_addr;
            } else {
                hop_info += "请求超时。";
            }
            
            // 记录当前跳的信息，每跳结束后添加换行符
            log += hop_info + "\n";
            
            // 如果已经达到目标，退出循环
            if (reached_target) {
                reached_destination = true;
                break;
            }
            
            // 重置io_context以准备下一个跳点测试
            io.restart();
        }  
        if (reached_destination) {
            // 延时让日志显示出来
            std::this_thread::sleep_for(std::chrono::milliseconds(1500));
            return "[通过：" + std::to_string(effective_hops) + "跳]";
        } else {
            return "[达到最大跳数限制30]";
        }
    }
    catch (std::exception& e) {
        log += "发生错误: " + std::string(e.what()) + "\n";
        return "[不通过]";
    }
}
